﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace EasySL.Core
{
    public class Response
    {
        public ResponseStatus Status { get; set; }
        public string Message { get; set; }
        public string DataString { get; set; }
        public object Data { get; set; }
        public object State { get; set; }
        
        public Response()
        {
            Status = ResponseStatus.Success;
            Data = null;
            Message = string.Empty;
            DataString = string.Empty;
        }

        public Response(object state)
            : this()
        {
            this.State = state;
        }

        public string Serialize()
        {
            return JavaScriptConvert.SerializeObject(this);
        }

        public void Deserialize(string jsonString, Type dataType)
        {
            if (dataType == null)
                dataType = typeof(string);
            
            this.DataString = jsonString;
            
            JObject root = JObject.Parse(jsonString);
            this.Message = (root["Message"] as JValue).Value.ToString();
            this.Status = JavaScriptConvert.DeserializeObject< ResponseStatus>((root["Status"] as JValue).Value.ToString());
            this.Data = JavaScriptConvert.DeserializeObject(root["Data"].ToString(), dataType);
        }

    }

    public enum ResponseStatus
    {
        Success = 0,
        BadRequest = 1,
        ServiceException = 2,
        UnknownFailure = 3
    }

}
